import * as ts from 'typescript'

// 定义一个正则表达式 DOUBLE_BYTE_REGEX
// [^\x00-\xff] 匹配任何不在 \x00-\xff 范围内的字符,即匹配双字节字符(如中文、日文、韩文等)
// g 表示全局匹配
const DOUBLE_BYTE_REGEX = /[^\x00-\xff]/g

/**
 * 去掉文件中的注释
 * @param code
 * @param fileName
 */
export function removeFileComment(code, fileName) {
  const printer = ts.createPrinter({ removeComments: true })
  const sourceFile = ts.createSourceFile(
    '',
    code,
    ts.ScriptTarget.ES2015,
    true,
    fileName.endsWith('.tsx') ? ts.ScriptKind.TSX : ts.ScriptKind.TS
  )
  return printer.printFile(sourceFile)
}

/**
 * 在源文件中查找中文词条
 * @param code 源代码
 * @param fileName 当前文件路径名
 */
export function transformChinese(code, fileName) {
  const templateString = {
    "funcName": "I18N.get"
  }
  const matches = []
  const ast = ts.createSourceFile('', code, ts.ScriptTarget.ES2015, true, ts.ScriptKind.TSX)
  const factory = ts.factory

  function generateKey(text) {
    const noCharText = text.replace(
      /[\u0021-\u007E\u00A1-\u00FF\u3001-\u301f\uff01-\uff0f\uff1a-\uff20\uff3b-\uff40\uff5b-\uff65]/g,
      ''
    )
    const pinYinArr = pinyin(noCharText, {
      style: 'tone2',
    })
    const pinYinStr = flatten(pinYinArr).join('_')

    return pinYinStr.length > 40 ? pinYinStr.substring(0, 40) : pinYinStr
  }

  const transformer = (context) => (rootNode) => {
    function visit(node) {
      switch (node.kind) {
        case ts.SyntaxKind.StringLiteral: {
          const { text } = node
          if (text.match(DOUBLE_BYTE_REGEX)) {
            // const textKey = generateKey(text)
            // 1. 在本地寻找词条，如果找到
            // const findEntry = entries.find((entry) => entry.key === textKey)
            // const langs = findEntry?.langs || {}
            // const key = findEntry?.key || textKey
            // const isMatch = !!findEntry
            matches.push(text)
            // if (isMatch) {
            //   const parentNodeKind = node.parent.kind
            //   const result =
            //     parentNodeKind === ts.SyntaxKind.JsxAttribute ? `{I18N.index.${key}}` : `I18N.index.${key}`
            //   return factory.createIdentifier(result)
            // }
          }
          break
        }
        case ts.SyntaxKind.JsxText: {
          const text = node.getText()
          let noCommentText = removeFileComment(text, fileName)
          if (noCommentText.match(DOUBLE_BYTE_REGEX)) {
            noCommentText = noCommentText.replace(';\n', '')
            // const textKey = generateKey(noCommentText)
            // const findEntry = entries.find((entry) => entry.key === textKey)
            // const langs = findEntry?.langs || {}
            // const key = findEntry?.key || textKey
            // const isMatch = !!findEntry
            matches.push(noCommentText)
            // if (isMatch) {
            //   return factory.createJsxText(`{I18N.index.${key}}`)
            // }
          }
          break
        }
        case ts.SyntaxKind.TemplateExpression: {
          const { pos, end } = node
          let text = code.slice(pos, end)
          if (text.match(DOUBLE_BYTE_REGEX)) {
            text.replace(/\$(?=\{)/g, '')
            // const textKey = generateKey(text)
            if (templateString && templateString.funcName) {
              // const findEntry = entries.find((entry) => entry.key === textKey)
              // const langs = findEntry?.langs || {}
              // const key = findEntry?.key || textKey
              // const isMatch = !!findEntry
              matches.push(text)
            } else {
              console.warn(`模板字符串：${fileName} ${text} 无法处理`)
            }
          }
          break
        }
      }
      return ts.visitEachChild(node, visit, context)
    }
    return ts.visitNode(rootNode, visit)
  }

  ts.transform(ast, [transformer]).transformed[0]

  return matches
}